﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
 

namespace MyVoteMVC.Common.Objects
{
    /*****************
     * 
     * 结构暂时按照
     * 整个邮件头
     * |------
     * 邮件体第一部分
     * 邮件体第一部分邮件头
     * |------  
     * 邮件体第二部分
     * 邮件体第二部分邮件头
     * |------
     * .
     * .
     * .
     * 邮件体第N部分
     * 邮件体第N部分邮件头
     * |------
     * 结束整个邮件
     * ******************/
    public class MailMethods
    {
        const string X_Mailer = "X-Mailer:Lucky Mail Sender V1.0";
        const string SP = "_______=__Part3.1415520";//内容分隔符
        const string FILE_HEADER = "Content-Type: application/octet-stream;name=\"{0}\""; //文件头
        //const string CONTENT_ENCODING = "Content-Transfer-Encoding: {0}";  //内容编码
        const string FILE_DESCRIPTION = "Content-Disposition:attachment;filename=\"{0}\"";  //文件注解

        public static string ReaderCode(Stream reader)
        {
            byte[] by = new byte[255];
            int size = reader.Read(by, 0, by.Length);
            string message = null;
            if (size > 0)
            {
                message = Encoding.ASCII.GetString(by);
            }
            return message.Substring(0,3);
        }

        public static void SendCommand(string cmd, Stream writer)
        {
            Write(cmd, Encoding.ASCII, writer);
        }

        public static void SendHeader(Stream writer, MailMessage message)
        {
            Write(Formatter.DateFormat(DateTime.Now), message.Encoding, writer); //日期

            //发件人
            if (string.IsNullOrEmpty(message.DisplayFrom))
            {
                Write(Formatter.FormFormat(Formatter.AddressFormat(message.From,message.DisplayFrom)), message.Encoding, writer); //发件人
            }
            else
            {
                Write(Formatter.FormFormat(message.From), message.Encoding, writer);
            }

            Write(Formatter.TosFormat(message.Tos), message.Encoding, writer); //收件人
            Write("REPLY-TO:" + message.From, message.Encoding, writer); //回复地址
            //抄送
            //密送
            Write(Formatter.PriorityFormat(message.Priority), message.Encoding, writer); //优先级
            Write(Formatter.SubjectFormat(message.Subject, message.Encoding), message.Encoding, writer); //标题
            Write(Formatter.EncodingFormat(EmailEncode.BASE64), message.Encoding, writer); //编码--------.....
            Write(X_Mailer, message.Encoding, writer); //发件人程序
            Write(Formatter.MessageIdFormat(System.Guid.NewGuid().ToString()), message.Encoding, writer);
            Write("MIME-Version:1.0", message.Encoding, writer);
            Write(Formatter.BoundaryFormat(SP), message.Encoding, writer); //定义邮件体类型和整个邮件内容分隔符
            Write(Formatter.BoundaryBeginFormat(SP), message.Encoding, writer); //设置正文部分开始分隔符
        }

        public static void SendBody(string body, Stream writer, Encoding encoding, bool isHtml)
        {
           
            Write(Formatter.BodyHeaderFormat(isHtml, encoding), encoding, writer);
            Write(Formatter.EncodingFormat(EmailEncode.BASE64), encoding, writer);
            Write("\r\n", encoding, writer);
            Write(Convert.ToBase64String(encoding.GetBytes(body)), encoding, writer);
            Write("", encoding, writer);
        }
        
        public static void SendAttchments(Dictionary<string, byte[]> attachmentData, Stream writer, Encoding encoding)
        {
            foreach (KeyValuePair<string, byte[]> kvp in attachmentData)
            {
                Write(Formatter.BoundaryBeginFormat(SP), encoding, writer); //设置附件部分开始分隔符
                Write(string.Format(FILE_HEADER, kvp.Key), encoding, writer); //文件头
                Write(Formatter.EncodingFormat(EmailEncode.BASE64), encoding, writer); //编码

                Write("\r\n", encoding, writer);
                Write(Convert.ToBase64String(kvp.Value), encoding, writer); //文件内容
                Write("", encoding, writer); //完成发送
            }
        }
        public static void SendAttchments(List<string> attchments, Stream writer, Encoding encoding)
        {
            foreach (string filePath in attchments)
            {
                byte[] fileDate;
                string fileName = "";
                //读取文件内容
                using (FileStream file = new FileStream(filePath, FileMode.Open))
                {

                    fileDate = new byte[Convert.ToInt32(file.Length)];
                    file.Read(fileDate, 0, fileDate.Length);
                    fileName = Path.GetFileName(filePath);
                }
                Write(Formatter.BoundaryBeginFormat(SP), encoding, writer); //设置附件部分开始分隔符
                Write(string.Format(FILE_HEADER, fileName), encoding, writer); //文件头
                Write(Formatter.EncodingFormat(EmailEncode.BASE64), encoding, writer); //编码

                Write("\r\n", encoding, writer);
                Write(Convert.ToBase64String(fileDate), encoding, writer); //文件内容
                Write("", encoding, writer); //完成发送
            }
        }

        public static void WriterEnd(Stream writer, Encoding encoding)
        {
            Write("", encoding, writer);
            Write(Formatter.BoundaryEndFormat(SP), encoding, writer);
            SendCommand(SmtpCommand.GetCommand(SmtpCommandType.END_DATA), writer);
        }

        private static void Write(string data, Encoding encoding, Stream writer)
        {
            if (writer.CanWrite)
            {
                int size = 255;
                byte[] datas = encoding.GetBytes(string.Format("{0}\r\n", data));
                if (datas.Length < size)
                {
                    writer.Write(datas, 0, datas.Length);
                }
                else
                {
                    for (int i = 0; i < datas.Length; i += size)
                    {
                        writer.Write(datas, i, datas.Length - i < size ? datas.Length - i : size);
                    }
                }
            }
        }


    }
}
